package com.by.mq;

import com.by.bean.Order;
import com.by.bean.OrderDetail;
import com.by.common.utils.RedisUtils;
import com.by.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class OrderConsumer {

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    OrderService orderService;

    /**
     * 只执行一次 初始化方法
     */
    @PostConstruct
    public void init() {
        log.info("消费者等待消费消息：");
    }

    /**
     * 监听订单队列
     *
     * @param message
     * @param channel
     */
    @RabbitListener(queues = {"orderQueue"})
    public void handlerOrder(Message message, Channel channel) {
        //获取消息
        String msg = new String(message.getBody());
        String[] tmp = msg.split("@");
        int userId = Integer.parseInt(tmp[0]);
        int goodsId = Integer.parseInt(tmp[1]);
        String orderNum = tmp[2];

        //生成订单
        String key = "goods:id:" + goodsId;
        //从缓存中  获取商品信息
        String price = redisUtils.get(key + ":price");
        String goodsname = redisUtils.get(key + ":goodsname");

        //订单信息
        Order order = new Order();
        order.setOrderNum(orderNum);
        order.setMoney(Double.parseDouble(price.toString()));
        order.setUserId(userId);

        //订单明细
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setNum(1);
        orderDetail.setGoodsname(goodsname.toString());
        orderDetail.setPrice(Double.parseDouble(price.toString()));
        orderDetail.setGoodsId(goodsId);
        List<OrderDetail> list = new ArrayList<>();
        list.add(orderDetail);
        order.setOrderDetails(list);

        //生成订单
        int rs = orderService.saveOrder(order);

        if (rs == 1) {
            //告诉 mq服务器 生成成功
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                log.error("消费者消费[" + msg + "]生成生育金失败");
                throw new RuntimeException(e);
            }
        } else {
            //失败
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


    }


    /**
     * 延迟队列
     * @param msg
     * @param channel
     */
    @RabbitListener(queues = {"lazyQueue"})
    public void handlerLazyOrder(Message msg, Channel channel) {
        String id = new String(msg.getBody());//订单id
        //查询订单状态   判断
        int rs = orderService.updateStatus(Integer.parseInt(id));
        if (rs == 1) {
            log.info("订单id=[" + id + "]的订单未支付已取消 ");
            //回库存
            //查询对应商品id 将内存中的库存加1  goods:id:1


        }

        //已经支付
        try {
            //确认
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}